﻿using System;
using System.IO;
using System.Net;
using System.Net.Sockets;

namespace MuYue.Common
{
    public class NetFileMetaInfo
    {
        /// <summary>
        /// 文件名
        /// </summary>
        public string Name { set; get; }
        /// <summary>
        /// 文件MD5值
        /// </summary>
        public string Md5Key { set; get; }
        /// <summary>
        /// 如果存在重名文件是否执行重命名操作
        /// </summary>
        public bool ReName { set; get; }
    }

    public class NetFile
    {

        public NetFile(string host, int port)
        {
            this.Host = host;
            this.Port = port;
        }


        public string Host { set; get; }
        public int Port { set; get; }

        public void SendFile(string fileName, bool reName)
        {
            if (string.IsNullOrWhiteSpace(fileName))
                throw new ArgumentNullException("fileName");
            if (!File.Exists(fileName))
                throw new Exception(fileName + "不存在");

            fileName = fileName.Replace("\\", "/");

            var info = new NetFileMetaInfo();
            info.Md5Key = Utility.Md5EncodingFile(fileName);
            info.Name = fileName.Substring(fileName.LastIndexOf("/") + 1);
            info.ReName = reName;

            var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            socket.Connect(new IPEndPoint(IPAddress.Parse(Host), Port));

            using (var t = new MuYue.Common.MuYueSocket(socket, 30 * 1000, 5000))
            {
                var str = Newtonsoft.Json.JsonConvert.SerializeObject(info);
                t.Send(str);
                using (var fs = File.OpenRead(fileName))
                {
                    t.SendFile(fs);
                }
            }
        }
    }
}
